var chalk = require('chalk');
var seeyonBuildConfig = require('../seeyonBuildConfig.js');
var FsUtils = require('../utils/FsUtils.js');
var fs = require("fs");
var paramsUtils = require("../utils/ParamsUtils.js");

const pluginName = 'AutoCompilePlugin';


class AutoCompilePlugin {
    apply(compiler) {
        // 自动编译插件主要用于代码提交
        //编译成功时时处理
        compiler.hooks.done.tap(
            pluginName,
            (error) => {
                console.log(chalk.green(`执行--->${pluginName}`));
                if(paramsUtils.isExist('production') ){

                    setTimeout(()=>{
                        let dir =  seeyonBuildConfig.outputDir;
                        console.log(dir);
                        // 创建路径
                        let dirs = dir.split('/');
                        console.log(dirs);
                        dirs.pop();
                        FsUtils.mkdirsSync(dirs.join('/'));
                        console.log(seeyonBuildConfig.buildDIr,seeyonBuildConfig.outputDir);
                        fs.rename(seeyonBuildConfig.buildDIr, seeyonBuildConfig.outputDir,()=>{
                            fs.mkdirSync(seeyonBuildConfig.buildDIr);
                            console.log(seeyonBuildConfig.buildHome,seeyonBuildConfig.buildDIr+'/'+seeyonBuildConfig.buildHome);
                            fs.renameSync(seeyonBuildConfig.buildHome, seeyonBuildConfig.buildDIr+'/'+seeyonBuildConfig.buildHome);
                        });
                    },1000)
                }

            }
        );
        // compiler.hooks.afterEmit.tapAsync(
        //     pluginName,
        //     (error, callback) => {
        //         console.log(chalk.green(`执行--->${pluginName}`));
        //             //FsUtils.copyDir(seeyonBuildConfig.buildDIr,seeyonBuildConfig.buildDIr+'_back');
        //             // setTimeout(()=>{
        //             //     let dir = seeyonBuildConfig.buildDIr + seeyonBuildConfig.outputDir;
        //             //     // 创建路径
        //             //     let dirs = dir.split('/');
        //             //     dirs.pop();
        //             //     FsUtils.mkdirsSync(dirs.join('/'));
        //             //     fs.renameSync(seeyonBuildConfig.buildDIr+'_back',dir);
        //             //
        //             // },200)
        //
        //     }
        // );

    }
}

module.exports = AutoCompilePlugin;